package cn.itsource.user.controller;

import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.basic.utils.RedisUtils;
import cn.itsource.user.domain.User;
import cn.itsource.user.domain.vo.UserVO;
import cn.itsource.user.service.IUserService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    /*
      { phone:'', code:'', password:'', passwordRepeat:'' }
           1.用什么类型接收参数
           2.后台的数据验证

           3.密码明文存储的问题（加密处理）
           4.存储到数据库

     */
    @PostMapping("/reg")
    public AjaxResult register(@RequestBody UserVO userVO){
        try {
            userService.regUser(userVO);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }

    }
    @PostMapping("/login")
    public AjaxResult login(@RequestBody HashMap<String,String> map){
        try {
            String username = map.get("username");
            String pwd = map.get("password");
            User user = userService.loginByUserName(username, pwd);
            //生成随机字符串
            String token = UUID.randomUUID().toString().replace('-', 'o');
            //java 对象  和 js  json对象如果可以转换
            String userJson = JSONObject.toJSONString(user);

            //需要把当前的登录用户存储到redis
            RedisUtils.INSTANCE.set(token,userJson,60*30);
            System.out.println("存储到redis里面的用户："+token+"       "+userJson);

            //把票据 和 用户都给前端服务器
            Map<String,Object> returnMap = new HashMap<>();
            returnMap.put("token",token);
            returnMap.put("user",user);

            return AjaxResult.me().setResultObj(returnMap);
        } catch (Exception e) {
            return new AjaxResult(e.getMessage());
        }

    }
}
